package fts.ftscontrol;

import java.util.HashMap;
import java.util.Iterator;

import fts.ftsmonitoring.ftsTaggers.IAutoTagger;
import fts.ftsdata.domain.ITag;
import fts.ftsdata.domain.ITaggedFile;
import fts.ftsdata.services.ILookupService;
import fts.ftsdata.services.ITaggingService;
import fts.ftsmonitoring.FileAction;
import fts.ftsmonitoring.IFileObserver;
import fts.ftsmonitoring.MonitoringStatus;
import fts.ftsmonitoring.Utils;


class FileChangeObserver implements IFileObserver
{
	private Facade facade;
	private ITaggingService taggingService;
	ILookupService lookupService;
	private HashMap<Class<?>, fts.ftsmonitoring.ftsTaggers.IAutoTagger> taggers = new HashMap<Class<?>, IAutoTagger>();

	FileChangeObserver(Facade facade, ITaggingService taggingService, ILookupService lookupService)
	{
		this.facade = facade;
		this.taggingService = taggingService;
		this.lookupService = lookupService;
	}
	public synchronized void addTagger(fts.ftsmonitoring.ftsTaggers.IAutoTagger tagger)
	{
		if (this.taggers.containsKey(tagger.getClass()))
		{
			this.taggers.remove(tagger.getClass());
		}
		this.taggers.put(tagger.getClass(), tagger);
	}

	public synchronized void removeTagger(IAutoTagger tagger)
	{
		this.removeTagger(tagger.getClass());
	}

	public synchronized void removeTagger(Class<?> taggerClass)
	{
		if (this.taggers.containsKey(taggerClass))
		{
			this.taggers.remove(taggerClass);
		}
	}
	
	public synchronized void applyTaggers(String fileName, ITaggingService taggingService)
	{
		Utils.applyTaggersMap(fileName, taggingService, taggers);
	}
	public void onFileChange(String srcFile, String destFile, FileAction action)
	{
		switch(action)
		{
			case COPY:
				break;
			case DELETE:
				try
				{
					facade.deleteFile(srcFile);
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case MOVE:
				try
				{
					ITaggedFile file1 = facade.getFileByName(srcFile);
					ITaggedFile file2 = taggingService.createTaggedFile(destFile);
					Iterator<? extends ITag> iter = file1.getAutoTagsIterator();
					while(iter.hasNext())
					{
						file2.addAutoTag(iter.next());
					}
					iter = file1.getManualTagsIterator();
					while(iter.hasNext())
					{
						file2.addManualTag(iter.next());
					}
					taggingService.saveTaggedFile(file2);
					taggingService.deleteTaggedFile(file1);
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case NEW:
				Utils.applyTaggersMap(srcFile, taggingService, taggers);
				break;
		}
	}

	public void onMonitoringStatusChange(MonitoringStatus status)
	{
		// TODO Auto-generated method stub

	}

}
